using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
using Newtonsoft.Json;

namespace GameOverlayWPF
{
    // 卡片项基类（用于方案和广告的统一显示）
    public interface ICardItem
    {
        string DisplayId { get; }
        bool IsAdvertisement { get; }
    }
    
    public class Scheme : ICardItem, INotifyPropertyChanged
    {
        private int _uses;
        
        public int Id { get; set; }
        public int UserId { get; set; }
        public string? UserName { get; set; }
        public string? UserAvatar { get; set; }
        public string? Category { get; set; }
        public string? WeaponName { get; set; }
        public string? Description { get; set; }
        public string? Price { get; set; }
        public DateTime? CreatedAt { get; set; }
        
        public int Uses
        {
            get => _uses;
            set
            {
                if (_uses != value)
                {
                    _uses = value;
                    OnPropertyChanged(nameof(Uses));
                }
            }
        }
        
        public string? SchemeContent { get; set; }
        
        // ========== 合作伙伴认证信息 ==========
        public string? PartnerType { get; set; }
        public string? PartnerLevel { get; set; }
        public string? PartnerBadge { get; set; }
        public string? PartnerLogo { get; set; }
        public string? SocialLink { get; set; }
        
        public event PropertyChangedEventHandler? PropertyChanged;
        
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        
        // 图片URL属性
        public string? ImageUrl => $"https://www.maqt.top/uploads/schemes/{Id}.png";
        
        // 显示掩码后的配置代码（后6位用*号）
        public string MaskedSchemeCode
        {
            get
            {
                if (string.IsNullOrEmpty(SchemeContent))
                    return string.Empty;
                
                if (SchemeContent.Length <= 6)
                    return new string('*', SchemeContent.Length);
                
                return SchemeContent.Substring(0, SchemeContent.Length - 6) + "******";
            }
        }
        
        // 只显示配置代码（后6位用*号）
        public string DisplaySchemeCode
        {
            get
            {
                return MaskedSchemeCode;
            }
        }
        
        // 格式化的创建时间显示
        public string FormattedCreatedAt
        {
            get
            {
                if (!CreatedAt.HasValue)
                    return "未知时间";
                
                var now = DateTime.Now;
                var createdDate = CreatedAt.Value;
                
                // 如果是今天，显示具体时间
                if (createdDate.Date == now.Date)
                    return createdDate.ToString("HH:mm");
                // 如果是昨天，显示"昨天 HH:mm"
                else if (createdDate.Date == now.Date.AddDays(-1))
                    return $"昨天 {createdDate.ToString("HH:mm")}";
                // 如果是今年，显示"MM-dd HH:mm"
                else if (createdDate.Year == now.Year)
                    return createdDate.ToString("MM-dd HH:mm");
                // 其他情况显示完整日期时间
                else
                    return createdDate.ToString("yyyy-MM-dd HH:mm");
            }
        }
        
        // ICardItem 实现
        public string DisplayId => $"scheme_{Id}";
        public bool IsAdvertisement => false;
        
        // ========== 认证徽章相关方法 ==========
        
        /// <summary>
        /// 是否为认证用户（合作伙伴）
        /// </summary>
        public bool IsPartner => 
            !string.IsNullOrEmpty(PartnerType) && 
            PartnerType != "none" && 
            !string.IsNullOrEmpty(PartnerLevel) && 
            PartnerLevel != "none";
        
        /// <summary>
        /// 获取认证徽章显示文本
        /// </summary>
        public string GetBadgeText()
        {
            if (!string.IsNullOrEmpty(PartnerBadge))
                return PartnerBadge;
            
            return PartnerType switch
            {
                "douyin" => "抖音",
                "bilibili" => "B站",
                "club" => "俱乐部",
                "other" => "认证",
                _ => "认证"
            };
        }
        
        /// <summary>
        /// 获取徽章图标URL（带默认值）
        /// </summary>
        public string GetBadgeLogoUrl()
        {
            return !string.IsNullOrEmpty(PartnerLogo) 
                ? PartnerLogo 
                : "pack://application:,,,/favicon.ico";
        }
        
        /// <summary>
        /// 获取徽章颜色（根据等级）
        /// </summary>
        public string GetBadgeColor()
        {
            return PartnerLevel switch
            {
                "gold" => "#FFD700",    // 金色
                "silver" => "#C0C0C0",  // 银色
                "bronze" => "#CD7F32",  // 铜色
                _ => "#4A9EFF"          // 默认蓝色
            };
        }
    }

    public class DatabaseManager
    {
        private static DatabaseManager? _instance;
        
        // API配置
        private const string ApiBase = "https://www.maqt.top";
        private const string ApiSchemes = "/api/schemes";
        private const string ApiSchemesAob = "/api/schemes_aob";
        private const string ApiWeaponCategories = "/api/weapon-categories";
        private const string ApiWeapons = "/api/weapons";
        private const string ApiReferer = "https://www.maqt.top/";
        private const string EncryptionKey = "maqt-delta-force-2024-secret-key-32";
        private static readonly HttpClient Http = new HttpClient
        {
            Timeout = TimeSpan.FromSeconds(10)
        };
        
        // 本地缓存
        private readonly Dictionary<string, CachedData<List<Scheme>>> _schemesCache = new Dictionary<string, CachedData<List<Scheme>>>();
        private readonly Dictionary<string, CachedData<List<string>>> _categoriesCache = new Dictionary<string, CachedData<List<string>>>();
        private readonly Dictionary<string, CachedData<List<string>>> _weaponsCache = new Dictionary<string, CachedData<List<string>>>();
        private readonly object _cacheLock = new object();
        private static readonly TimeSpan CacheExpiration = TimeSpan.FromMinutes(10); // 缓存10分钟，减少API调用
        private static readonly TimeSpan LongCacheExpiration = TimeSpan.FromMinutes(30); // 分类、武器等静态数据缓存更久
        
        public static DatabaseManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new DatabaseManager();
                }
                return _instance;
            }
        }

        private DatabaseManager()
        {
        }
        
        // 缓存数据结构
        private class CachedData<T>
        {
            public T Data { get; set; }
            public DateTime CachedTime { get; set; }
            
            public bool IsExpired(TimeSpan expiration)
            {
                return DateTime.Now - CachedTime > expiration;
            }
        }

        public async Task<List<Scheme>> GetSchemesAsync()
        {
            return await GetSchemesAsync(null);
        }
        
        public async Task<List<Scheme>> GetSchemesAsync(string? category = null, string? weaponName = null, string? priceRange = null, string? searchText = null, string? sortBy = null)
        {
            // 生成缓存键
            var cacheKey = $"schemes_{category}_{weaponName}_{priceRange}_{searchText}_{sortBy}";
            
            // 检查缓存
            lock (_cacheLock)
            {
                if (_schemesCache.TryGetValue(cacheKey, out var cached) && !cached.IsExpired(CacheExpiration))
                {
                    System.Diagnostics.Debug.WriteLine($"从缓存加载方案数据: {cacheKey}");
                    return new List<Scheme>(cached.Data); // 返回副本
                }
            }
            
            var schemes = new List<Scheme>();

            try
            {
                var queryParams = new List<string>();
                
                // API参数映射
                if (!string.IsNullOrEmpty(category))
                    queryParams.Add($"weaponCategory={Uri.EscapeDataString(category)}");
                
                if (!string.IsNullOrEmpty(weaponName))
                    queryParams.Add($"weaponName={Uri.EscapeDataString(weaponName)}");
                
                if (!string.IsNullOrEmpty(searchText))
                    queryParams.Add($"search={Uri.EscapeDataString(searchText)}");
                
                // 价格范围筛选
                if (!string.IsNullOrEmpty(priceRange))
                {
                    switch (priceRange)
                    {
                        case "0-15万":
                            queryParams.Add("minPrice=0");
                            queryParams.Add("maxPrice=15");
                            break;
                        case "16-30万":
                            queryParams.Add("minPrice=16");
                            queryParams.Add("maxPrice=30");
                            break;
                        case "31-60万":
                            queryParams.Add("minPrice=31");
                            queryParams.Add("maxPrice=60");
                            break;
                        case "60万以上":
                            queryParams.Add("minPrice=60");
                            break;
                    }
                }
                
                // 排序参数
                var sort = sortBy == "latest" || sortBy == "hot" ? sortBy : "hot";
                queryParams.Add($"sort={sort}");
                
                queryParams.Add("page=1");
                
                // 根据筛选条件决定加载数量 - 增加初始加载量但限制最大值
                bool isAllView = string.IsNullOrEmpty(category) && string.IsNullOrEmpty(weaponName) && string.IsNullOrEmpty(searchText) && string.IsNullOrEmpty(priceRange);
                queryParams.Add(isAllView ? "limit=60" : "limit=20"); // 增加加载量，减少请求次数
                
                var url = $"{ApiBase}{ApiSchemes}?{string.Join("&", queryParams)}";
                
                var root = await GetApiRootAsync(url);
                if (root == null || root.data == null)
                    return schemes;
                
                foreach (var item in root.data)
                {
                    var avatar = SafeGetString(item.avatar);
                    System.Diagnostics.Debug.WriteLine($"[烽火地带] 原始avatar: '{avatar}'");
                    
                    // 如果头像是相对路径，拼接完整URL
                    if (!string.IsNullOrEmpty(avatar) && !avatar.StartsWith("http"))
                    {
                        avatar = $"https://www.maqt.top{(avatar.StartsWith("/") ? "" : "/")}{avatar}";
                        System.Diagnostics.Debug.WriteLine($"[烽火地带] 拼接后avatar: '{avatar}'");
                    }
                    
                    var scheme = new Scheme
                    {
                        Id = SafeGetInt(item.id),
                        UserId = SafeGetInt(item.user_id),
                        UserName = SafeGetString(item.username),
                        UserAvatar = avatar,
                        Category = SafeGetString(item.category),
                        WeaponName = SafeGetString(item.weapon_name),
                        Description = SafeGetString(item.description),
                        Price = SafeGetString(item.price),
                        Uses = SafeGetInt(item.uses),
                        SchemeContent = SafeGetString(item.scheme_content),
                        CreatedAt = SafeGetDateTime(item.created_at),
                        // 认证信息
                        PartnerType = SafeGetString(item.partner_type),
                        PartnerLevel = SafeGetString(item.partner_level),
                        PartnerBadge = SafeGetString(item.partner_badge),
                        PartnerLogo = SafeGetString(item.partner_logo),
                        SocialLink = SafeGetString(item.social_link)
                    };
                    schemes.Add(scheme);
                }
                
                // 添加到缓存
                lock (_cacheLock)
                {
                    _schemesCache[cacheKey] = new CachedData<List<Scheme>>
                    {
                        Data = schemes,
                        CachedTime = DateTime.Now
                    };
                    
                    // 限制缓存大小
                    if (_schemesCache.Count > 50)
                    {
                        var oldestKey = _schemesCache.OrderBy(x => x.Value.CachedTime).First().Key;
                        _schemesCache.Remove(oldestKey);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取方案数据失败: {ex.Message}");
            }

            return schemes;
        }
        
        public async Task<List<string>> GetCategoriesAsync()
        {
            var cacheKey = "categories";
            
            // 检查缓存
            lock (_cacheLock)
            {
                if (_categoriesCache.TryGetValue(cacheKey, out var cached) && !cached.IsExpired(CacheExpiration))
                {
                    System.Diagnostics.Debug.WriteLine("从缓存加载分类数据");
                    return new List<string>(cached.Data);
                }
            }
            
            var categories = new List<string>();

            try
            {
                var url = $"{ApiBase}{ApiWeaponCategories}";
                var resp = await GetApiPlainAsync(url);
                if (resp?.data != null)
                {
                    foreach (var item in resp.data)
                    {
                        var name = SafeGetString(item.category);
                        if (!string.IsNullOrEmpty(name))
                            categories.Add(name);
                    }
                }
                
                // 添加到缓存
                lock (_cacheLock)
                {
                    _categoriesCache[cacheKey] = new CachedData<List<string>>
                    {
                        Data = categories,
                        CachedTime = DateTime.Now
                    };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取分类数据失败: {ex.Message}");
            }

            return categories;
        }
        
        public async Task<List<string>> GetWeaponsAsync(string? category = null)
        {
            var cacheKey = $"weapons_{category}";
            
            // 检查缓存
            lock (_cacheLock)
            {
                if (_weaponsCache.TryGetValue(cacheKey, out var cached) && !cached.IsExpired(CacheExpiration))
                {
                    System.Diagnostics.Debug.WriteLine($"从缓存加载武器数据: {category ?? "全部"}");
                    return new List<string>(cached.Data);
                }
            }
            
            var weapons = new List<string>();

            try
            {
                var qp = string.IsNullOrEmpty(category) ? "" : $"?category={Uri.EscapeDataString(category)}";
                var url = $"{ApiBase}{ApiWeapons}{qp}";
                var resp = await GetApiPlainAsync(url);
                if (resp?.data != null)
                {
                    foreach (var item in resp.data)
                    {
                        var name = SafeGetString(item.display_name);
                        if (string.IsNullOrEmpty(name))
                            name = SafeGetString(item.weapon_name);
                        if (!string.IsNullOrEmpty(name))
                            weapons.Add(name);
                    }
                }
                
                // 添加到缓存
                lock (_cacheLock)
                {
                    _weaponsCache[cacheKey] = new CachedData<List<string>>
                    {
                        Data = weapons,
                        CachedTime = DateTime.Now
                    };
                    
                    // 限制缓存大小
                    if (_weaponsCache.Count > 20)
                    {
                        var oldestKey = _weaponsCache.OrderBy(x => x.Value.CachedTime).First().Key;
                        _weaponsCache.Remove(oldestKey);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取武器数据失败: {ex.Message}");
            }

            return weapons;
        }
        
        // 从schemes_aob表获取方案（全面战场模式，不包含价格字段）
        public async Task<List<Scheme>> GetSchemesAobAsync(string? category = null, string? weaponName = null, string? searchText = null, string? sortBy = null)
        {
            // 生成缓存键
            var cacheKey = $"schemes_aob_{category}_{weaponName}_{searchText}_{sortBy}";
            
            // 检查缓存
            lock (_cacheLock)
            {
                if (_schemesCache.TryGetValue(cacheKey, out var cached) && !cached.IsExpired(CacheExpiration))
                {
                    System.Diagnostics.Debug.WriteLine($"从缓存加载AOB方案数据: {cacheKey}");
                    return new List<Scheme>(cached.Data);
                }
            }
            
            var schemes = new List<Scheme>();

            try
            {
                var queryParams = new List<string>();
                
                if (!string.IsNullOrEmpty(category))
                    queryParams.Add($"weaponCategory={Uri.EscapeDataString(category)}");
                
                if (!string.IsNullOrEmpty(weaponName))
                    queryParams.Add($"weaponName={Uri.EscapeDataString(weaponName)}");
                
                if (!string.IsNullOrEmpty(searchText))
                    queryParams.Add($"search={Uri.EscapeDataString(searchText)}");
                
                var sort = sortBy == "latest" || sortBy == "hot" ? sortBy : "hot";
                queryParams.Add($"sort={sort}");
                queryParams.Add("page=1");
                
                bool isAllAob = string.IsNullOrEmpty(category) && string.IsNullOrEmpty(weaponName) && string.IsNullOrEmpty(searchText);
                queryParams.Add(isAllAob ? "limit=48" : "limit=12");
                
                var url = $"{ApiBase}{ApiSchemesAob}?{string.Join("&", queryParams)}";
                
                var root = await GetApiRootAsync(url);
                if (root == null || root.data == null)
                    return schemes;
                
                foreach (var item in root.data)
                {
                    var avatar = SafeGetString(item.avatar);
                    System.Diagnostics.Debug.WriteLine($"[全面战场] 原始avatar: '{avatar}'");
                    
                    // 如果头像是相对路径，拼接完整URL
                    if (!string.IsNullOrEmpty(avatar) && !avatar.StartsWith("http"))
                    {
                        avatar = $"https://www.maqt.top{(avatar.StartsWith("/") ? "" : "/")}{avatar}";
                        System.Diagnostics.Debug.WriteLine($"[全面战场] 拼接后avatar: '{avatar}'");
                    }
                    
                    var scheme = new Scheme
                    {
                        Id = SafeGetInt(item.id),
                        UserId = SafeGetInt(item.user_id),
                        UserName = SafeGetString(item.username),
                        UserAvatar = avatar,
                        Category = SafeGetString(item.category),
                        WeaponName = SafeGetString(item.weapon_name),
                        Description = SafeGetString(item.description),
                        Price = null, // AOB模式没有价格
                        Uses = SafeGetInt(item.uses),
                        SchemeContent = SafeGetString(item.scheme_content),
                        CreatedAt = SafeGetDateTime(item.created_at),
                        // 认证信息
                        PartnerType = SafeGetString(item.partner_type),
                        PartnerLevel = SafeGetString(item.partner_level),
                        PartnerBadge = SafeGetString(item.partner_badge),
                        PartnerLogo = SafeGetString(item.partner_logo),
                        SocialLink = SafeGetString(item.social_link)
                    };
                    schemes.Add(scheme);
                }
                
                // 添加到缓存
                lock (_cacheLock)
                {
                    _schemesCache[cacheKey] = new CachedData<List<Scheme>>
                    {
                        Data = schemes,
                        CachedTime = DateTime.Now
                    };
                    
                    // 限制缓存大小
                    if (_schemesCache.Count > 50)
                    {
                        var oldestKey = _schemesCache.OrderBy(x => x.Value.CachedTime).First().Key;
                        _schemesCache.Remove(oldestKey);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取方案数据(AOB)失败: {ex.Message}");
            }

            return schemes;
        }
        
        // 从schemes_aob表获取分类列表
        public async Task<List<string>> GetCategoriesAobAsync()
        {
            return await GetCategoriesAsync(); // AOB和普通模式使用相同的分类API
        }
        
        // 从schemes_aob表获取武器列表
        public async Task<List<string>> GetWeaponsAobAsync(string? category = null)
        {
            return await GetWeaponsAsync(category); // AOB和普通模式使用相同的武器API
        }
        
        // ========== API辅助方法 ==========
        private static async Task<dynamic?> GetApiRootAsync(string url)
        {
            try
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    request.Headers.Referrer = new Uri(ApiReferer);
                    var response = await Http.SendAsync(request);
                    var body = await response.Content.ReadAsStringAsync();
                    var json = JsonConvert.DeserializeObject<dynamic>(body);
                    if (json == null) return null;
                    
                    if (json.encrypted == true)
                    {
                        string iv = json.iv?.ToString() ?? string.Empty;
                        string dataHex = json.data?.ToString() ?? string.Empty;
                        var decrypted = DecryptData(iv, dataHex);
                        return JsonConvert.DeserializeObject<dynamic>(decrypted);
                    }
                    return json;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"API调用失败: {ex.Message}");
            }
            return null;
        }
        
        private static async Task<dynamic?> GetApiPlainAsync(string url)
        {
            try
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    request.Headers.Referrer = new Uri(ApiReferer);
                    var response = await Http.SendAsync(request);
                    var body = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(body);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"API调用失败: {ex.Message}");
            }
            return null;
        }
        
        private static string DecryptData(string ivHex, string dataHex)
        {
            var key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(EncryptionKey));
            var iv = HexToBytes(ivHex);
            var cipher = HexToBytes(dataHex);
            
            using (var aes = Aes.Create())
            {
                aes.Key = key;
                aes.IV = iv;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                using (var decryptor = aes.CreateDecryptor())
                {
                    var plaintext = decryptor.TransformFinalBlock(cipher, 0, cipher.Length);
                    return Encoding.UTF8.GetString(plaintext);
                }
            }
        }
        
        private static byte[] HexToBytes(string hex)
        {
            if (string.IsNullOrEmpty(hex)) return Array.Empty<byte>();
            var bytes = new byte[hex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
                bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            return bytes;
        }
        
        private static string? SafeGetString(dynamic v)
        {
            try { return v == null ? null : (string?)Convert.ToString(v); } catch { return null; }
        }
        
        private static int SafeGetInt(dynamic v)
        {
            try { return v == null ? 0 : Convert.ToInt32(v); } catch { return 0; }
        }
        
        private static DateTime? SafeGetDateTime(dynamic v)
        {
            try 
            { 
                if (v == null) return null;
                return DateTime.TryParse(Convert.ToString(v), out DateTime result) ? result : null;
            } 
            catch { return null; }
        }
    }
}
